<template>
  <el-container class="container">
    <el-main>
      <el-form class="form" @keydown.native.enter="login">
        <el-form-item class="form-item">
          <label class="form-title">极光IDC运营管理平台</label>
        </el-form-item>
        <el-form-item class="form-item">
          <el-input v-model="username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item class="form-item">
          <el-input v-model="password" placeholder="请输入用户名" type="password"></el-input>
        </el-form-item>
        <el-form-item class="form-item">
          <el-button
            class="form-button"
            type="primary"
            @click="login"
            :loading="btnValue !== '登录'"
            :disabled="!this.username || !this.password"
          >{{btnValue}}</el-button>
        </el-form-item>
      </el-form>
    </el-main>
  </el-container>
</template>
<script>
import * as userCenterApi from '../api/userCenterApi'
import { Message } from 'element-ui'
import Cookies from 'js-cookie'
import * as utils from '../common/utils'

export default {
  data() {
    return {
      username: '',
      password: '',
      btnValue: '登录'
    }
  },
  methods: {
    login() {
      if (utils.isEmpty(this.username) || utils.isEmpty(this.password)) {
        return
      }
      this.btnValue = '登录中...'
      userCenterApi.login(this.username, this.password).then(
        data => {
          this.setCookies(data)
          this.$router.push({
            name: 'WorkOrderList',
            params: { listType: '1' }
          })
        },
        error => {
          this.btnValue = '登录'
          this.username = ''
          this.password = ''
          Message.error(error.message)
        }
      )
    },
    setCookies(data) {
      let option = { expires: 7, path: '/' }
      Cookies.set('JSESSIONID', data.JSESSIONID, option)
      Cookies.set('TOKEN_KEY', data.JSESSIONID, option)
      Cookies.set('account', data.account, option)
      Cookies.set('userName', data.userName, option)
      Cookies.set('useDefaultPassword', data.useDefaultPassword, option)
      Cookies.set('roleInfo', data.roleinfo, option)
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;

  .form {
    width: 300px;
    margin: auto;

    .form-item {
      margin-bottom: 20px;

      .form-title {
        font-size: 18px;
        font-weight: bold;
      }

      .form-button {
        width: 100%;
        height: 40px;
      }
    }
  }
}
</style>
